<template>
  <el-dialog ref="dialog" width="50%" :close-on-click-modal="false" :close-on-press-escape="false">
    <slot />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button
          v-if="showComfirm"
          type="primary"
          :loading="confirmLoading"
          @click="handleConfirm"
          >确 定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import type { PropType } from 'vue'
import type { IElDialog } from '@/common/types/element-plus'
import { ElMessage } from 'element-plus'

export default defineComponent({
  props: {
    /**
     * 确认按钮绑定的事件
     */
    confirm: {
      type: Function as PropType<() => Promise<void>>,
      default: () => Promise.resolve()
    },
    /**
     * 是否显示确认按钮
     */
    showComfirm: {
      type: Boolean,
      default: true
    }
  },
  setup(props) {
    const dialog = ref<IElDialog | null>(null)
    const confirmLoading = ref(false)

    const handleCancel = () => {
      if (dialog.value) {
        dialog.value.visible = false
      }
    }
    const handleConfirm = async () => {
      confirmLoading.value = true
      // emit('confirm')
      if (!props.confirm) {
        ElMessage.warning('没有提交方法')
      } else {
        try {
          debugger
          await props.confirm().finally(() => {
            confirmLoading.value = false
          })
        } catch (error) {
          ElMessage.warning(error.message)
          confirmLoading.value = false
        }
      }
    }
    return {
      dialog,
      confirmLoading,
      handleCancel,
      handleConfirm
    }
  }
})
</script>

<style lang="scss" scoped></style>
